package org.sys.transporttrainsys.service;

import org.sys.transporttrainsys.dto.LearningStatistics;
import org.sys.transporttrainsys.entity.StudentLearningStatus;
import org.sys.transporttrainsys.repository.StudentLearningStatusRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class StudentLearningStatusService {

    @Autowired
    private StudentLearningStatusRepository repository;

    // 获取所有学员学习情况
    public List<StudentLearningStatus> getAllLearningStatuses() {
        return repository.findAll();
    }

    // 根据学生 ID 获取学习情况
    public List<StudentLearningStatus> getByStudentId(Long studentId) {
        return repository.findByStudentId(studentId); // 假设 repository 中有这个方法
    }

    // 根据培训计划 ID 获取学习情况
    public List<StudentLearningStatus> getByTrainingPlanId(Long trainingPlanId) {
        return repository.findByTrainingPlanId(trainingPlanId); // 假设 repository 中有这个方法
    }

    // 获取学习统计信息
    public List<LearningStatistics> getStatistics() {
        List<StudentLearningStatus> statuses = repository.findAll();

        // 按培训计划分组
        Map<Long, List<StudentLearningStatus>> groupedByTrainingPlan = statuses.stream()
                .collect(Collectors.groupingBy(status -> status.getTrainingPlan().getId()));

        return groupedByTrainingPlan.values().stream()
                .map(trainingPlanStatuses -> {
                    long trainingPlanId = trainingPlanStatuses.get(0).getTrainingPlan().getId();
                    String trainingPlanName = trainingPlanStatuses.get(0).getTrainingPlan().getName();
                    double averageProgress = trainingPlanStatuses.stream()
                            .mapToDouble(StudentLearningStatus::getProgress)
                            .average().orElse(0);
                    long completedCount = trainingPlanStatuses.stream()
                            .filter(status -> "完成".equals(status.getStatus())) // 假设有完成状态
                            .count();
                    int totalParticipants = trainingPlanStatuses.size();
                    double completionRate = totalParticipants > 0 ? (double) completedCount / totalParticipants * 100 : 0;

                    return new LearningStatistics(trainingPlanId, trainingPlanName, averageProgress, completionRate, totalParticipants, (int) completedCount);
                })
                .collect(Collectors.toList());
    }

    // 其他方法（如下载报表）可以在这里添加
}